package com.zensun.common.utils.weixin;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zensun.common.config.WeChatProperties;
import com.zensun.common.constant.Constants;
import com.zensun.common.core.redis.RedisCache;
import com.zensun.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SubscribeMessageUtils {

    public static final String ASSIGN_ORDER_TOMEMBER_NOTE = "已为您指派服务人员，请注意接听电话。";
    public static final String ASSIGN_ORDER_TOPURIFIER_NOTE = "您已成功接单，请即刻前往服务地点！";
    public static final String CONTRACT_ORDER_TOMEMBER_NOTE = "服务人员已改约时间，请知悉。";
    public static final String OVER_TIME_TOPURIFIER_NOTE = "您已超时，请尽快前往服务地点完成签到！";
    private static WeChatProperties weChatProperties = SpringUtils.getBean(WeChatProperties.class);
    private static RedisCache redisCache = SpringUtils.getBean(RedisCache.class);

    /**
     * 获取小程序全局唯一后台接口调用凭据（access_token）
     *
     * @return 获取access_token
     */
    public static String getAccessToken() {
        String access_token = "";

        Object flag = redisCache.getCacheObject(Constants.WECHAT_ACCESS_TOKEN);
        if (flag != null) {
            access_token = (String) redisCache.getCacheObject(Constants.WECHAT_ACCESS_TOKEN);
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append("grant_type=" + weChatProperties.getGrantType());
            sb.append("&appid=" + weChatProperties.getAppId());
            sb.append("&secret=" + weChatProperties.getSecret());
            String reqUrl = sb.toString();
            log.info("getAccessToken reqUrl:{}", reqUrl);
            try {
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("grant_type", weChatProperties.getGrantType());
                paramMap.put("appid", weChatProperties.getAppId());
                paramMap.put("secret", weChatProperties.getSecret());
                String s = HttpUtil.get(weChatProperties.getGetAccessTokenUrl(), paramMap);
//                String s = HttpUtils.sendGet(weChatProperties.getGetAccessTokenUrl(), sb.toString());
                JSONObject json = JSONObject.parseObject(s);
                log.info("getAccessToken json:{}", json);
                access_token = (String) json.get("access_token");
                redisCache.setCacheObject(Constants.WECHAT_ACCESS_TOKEN, access_token, 90, TimeUnit.MINUTES);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return access_token;
    }

    /**
     * 订单指派后给用户发送消息
     *
     * @param touser openId
     * @return
     */
    public static boolean assignOrderToMemberSubscribe(String token, String touser, Long orderId, String itemName, Date reserveTime, String cneeAddress) {
        boolean isSuccess = true;

        String url = weChatProperties.getSubscribeSendUrl() + token;
        Map<String, Object> param = new HashMap<>();
        param.put("touser", touser);
        param.put("template_id", weChatProperties.getAssignMemberTemplateId());
        param.put("page", weChatProperties.getAssignMemberPageUrl() + orderId);
        if (weChatProperties.getDeveloper()) {
            param.put("miniprogram_state", "developer");
        }
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> thing14 = new HashMap<>();
        thing14.put("value", itemName);

        Map<String, Object> time17 = new HashMap<>();
        time17.put("value", DateUtil.format(reserveTime, "yyyy-MM-dd HH:mm:ss"));

        Map<String, Object> thing2 = new HashMap<>();
        thing2.put("value", cneeAddress);

        Map<String, Object> thing12 = new HashMap<>();
        thing12.put("value", ASSIGN_ORDER_TOMEMBER_NOTE);

        data.put("thing14", thing14);
        data.put("time17", time17);
        data.put("thing2", thing2);
        data.put("thing12", thing12);
        param.put("data", data);
        log.info("assignOrderToMemberSubscribe param:{}", JSON.toJSONString(param));

        String result = null;
        try {
            result = HttpUtil.post(url, param);
            log.info("assignOrderToMemberSubscribe result:{}", result);
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * 订单预约后给用户发送消息
     *
     * @param touser openId
     * @return
     */
    public static boolean contractOrderToMemberSubscribe(String token, String touser, Long orderId, String itemName, Date reserveTime, String cneeAddress) {
        boolean isSuccess = true;

        String url = weChatProperties.getSubscribeSendUrl() + token;
        Map<String, Object> param = new HashMap<>();
        param.put("touser", touser);
        param.put("template_id", weChatProperties.getContractOrderTemplateId());
        param.put("page", weChatProperties.getContractOrderPageUrl() + orderId);
        if (weChatProperties.getDeveloper()) {
            param.put("miniprogram_state", "developer");
        }
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> thing1 = new HashMap<>();
        thing1.put("value", itemName);

        Map<String, Object> thing2 = new HashMap<>();
        thing2.put("value", cneeAddress);

        Map<String, Object> time3 = new HashMap<>();
        time3.put("value", DateUtil.format(reserveTime, "yyyy-MM-dd HH:mm:ss"));


        Map<String, Object> thing4 = new HashMap<>();
        thing4.put("value", CONTRACT_ORDER_TOMEMBER_NOTE);

        data.put("thing1", thing1);
        data.put("thing2", thing2);
        data.put("time3", time3);
        data.put("thing4", thing4);
        param.put("data", data);
        log.info("contractOrderToMemberSubscribe param:{}", JSON.toJSONString(param));

        String result = null;
        try {
            result = HttpUtil.post(url, param);
            log.info("contractOrderToMemberSubscribe result:{}", result);
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * 订单指派后给保洁发送消息
     *
     * @param touser openId
     * @return
     */
    public static boolean assignOrderToPurifierSubscribe(String token, String touser, Long orderId, String itemName, Date reserveTime, String cneeAddress) {
        boolean isSuccess = true;

        String url = weChatProperties.getSubscribeSendUrl() + token;
        Map<String, Object> param = new HashMap<>();
        param.put("touser", touser);
        param.put("template_id", weChatProperties.getAssignPurifierTemplateId());
        param.put("page", weChatProperties.getAssignPurifierPageUrl() + orderId);
        if (weChatProperties.getDeveloper()) {
            param.put("miniprogram_state", "developer");
        }
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> thing2 = new HashMap<>();
        thing2.put("value", itemName);

        Map<String, Object> date4 = new HashMap<>();
        date4.put("value", DateUtil.format(reserveTime, "yyyy-MM-dd HH:mm:ss"));

        Map<String, Object> thing10 = new HashMap<>();
        thing10.put("value", cneeAddress);


        Map<String, Object> thing12 = new HashMap<>();
        thing12.put("value", ASSIGN_ORDER_TOPURIFIER_NOTE);

        data.put("thing2", thing2);
        data.put("date4", date4);
        data.put("thing10", thing10);
        data.put("thing12", thing12);
        param.put("data", data);
        log.info("assignOrderToPurifierSubscribe param:{}", JSON.toJSONString(param));

        String result = null;
        try {
            result = HttpUtil.post(url, param);
            log.info("assignOrderToPurifierSubscribe result:{}", result);
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }
        return isSuccess;
    }


    /**
     * 保洁超时未签到
     *
     * @param touser openId
     * @return
     */
    public static boolean overTimeToPurifierSubscribe(String token, String touser, Long orderId, String itemName, Date reserveTime, String cneeAddress) {
        boolean isSuccess = true;

        String url = weChatProperties.getSubscribeSendUrl() + token;
        Map<String, Object> param = new HashMap<>();
        param.put("touser", touser);
        param.put("template_id", weChatProperties.getOverTimeTemplateId());
        param.put("page", weChatProperties.getOverTimePageUrl() + orderId);
        if (weChatProperties.getDeveloper()) {
            param.put("miniprogram_state", "developer");
        }
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> thing1 = new HashMap<>();
        thing1.put("value", itemName);

        Map<String, Object> thing2 = new HashMap<>();
        thing2.put("value", cneeAddress);

        Map<String, Object> time3 = new HashMap<>();
        time3.put("value", DateUtil.format(reserveTime, "yyyy-MM-dd HH:mm:ss"));


        Map<String, Object> thing4 = new HashMap<>();
        thing4.put("value", OVER_TIME_TOPURIFIER_NOTE);

        data.put("thing1", thing1);
        data.put("thing2", thing2);
        data.put("time3", time3);
        data.put("thing4", thing4);
        param.put("data", data);
        log.info("overTimeToPurifierSubscribe param:{}", JSON.toJSONString(param));

        String result = null;
        try {
            result = HttpUtil.post(url, param);
            log.info("overTimeToPurifierSubscribe result:{}", result);
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
        }
        return isSuccess;
    }
}
